using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace NoORM.Core.DbDialect
{
    public class MySqlDialect:IDbDialect
    {
        public string BuildParameterName(string parameterName)
        {
            return "?" + parameterName;
        }

        public string CreateParameterName(string parameterName)
        {
            return "?" + parameterName;
        }

        public string WrapFieldName(string tableOrFieldName)
        {
            return "`" + tableOrFieldName + "`";
        }

        public string DeleteFrom()
        {
            return "FROM";
        }

        public string GetPageSql(string sql, string orderby, int pageSize, int pageIndex)
        {
            if (string.IsNullOrEmpty(orderby))
            {
                orderby = "now()";
            }
            else
            {
                string[] fields = orderby.Split(',');
                foreach (string item in fields)
                {
                    string fieldName = item.Split(' ')[0];
                    Regex reg = new Regex($@"\b{fieldName}\b");
                    orderby = reg.Replace(orderby, this.WrapFieldName(fieldName));
                }
            }
            long firstRow = pageIndex * pageSize;
            //long endRow = (pageIndex + 1) * pageSize;
            sql = @$"{sql} order by {orderby} limit {firstRow},{pageSize}";
            return sql;
        }
    }
}
